/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    vector<int> path;
    vector<vector<int>> ret;
    void _pathSum(TreeNode* root,int targetSum,int sum){
    if (root == nullptr) {
            return;
        }
        // 更新当前路径的和
        sum += root->val;
        path.push_back(root->val);
        // 检查是否到达叶子节点且路径和等于目标值
        if (sum == targetSum && root->left == nullptr && root->right == nullptr) {
            ret.push_back(path); // 添加路径的副本
        } else {
            _pathSum(root->left, targetSum, sum);
            _pathSum(root->right, targetSum, sum);
        }
        // 回溯，移除当前节点
        path.pop_back();
    }
    vector<vector<int>> pathSum(TreeNode* root, int targetSum) {
        _pathSum(root,targetSum,0);
        return  ret;
    }
};